package li.webqq.ui;

import java.awt.AWTEvent;
import java.awt.Button;
import java.awt.Component;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.WindowEvent;
import java.net.URL;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import li.webqq.WebQq;
import li.webqq.api.CheckResponse;
import li.webqq.api.GetUserFriends2Response;
import li.webqq.api.Poll2Response;
import li.webqq.api.Poll2Response.MessageHandler;
import li.webqq.model.Message;
import li.webqq.model.User;

public class MainWin extends JFrame {
    private static final long serialVersionUID = -6567949351315362940L;

    private TrayIcon trayIcon;
    private JTabbedPane tabbedPane;

    private List<User> users;

    private WebQq webQq = new WebQq();

    public static void main(String[] args) throws Exception {
        new MainWin();
    }

    public MainWin() {
        try {
            enableEvents(AWTEvent.WINDOW_EVENT_MASK);
            setTitle("主窗口");
            tabbedPane = new JTabbedPane();
            addLoginPanel();

            add(tabbedPane);
            setBounds(100, 100, 1100, 680);
            setVisible(true);
            addTrayIcon();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addLoginPanel() {
        final JTextField verifyCodeField = new JTextField(20);
        final JLabel verifyCodeData = new JLabel();

        final JPanel panel = new JPanel();
        JLabel usernameLabel = new JLabel("用户名");
        panel.add(usernameLabel);
        final JTextField usernameField = new JTextField(20);
        usernameField.requestFocus();
        usernameField.addFocusListener(new FocusListener() {
            public void focusLost(FocusEvent e) {
                webQq.setQq(usernameField.getText());
                CheckResponse checkResponse = webQq.check();
                if (checkResponse.needGetImage()) {
                    ImageIcon imageIcon = new ImageIcon(webQq.getImage().getData());
                    verifyCodeData.setIcon(imageIcon);
                } else {
                    verifyCodeField.setText(checkResponse.getVerifyCode()); // 不需要验证码
                }
            }

            public void focusGained(FocusEvent e) {}
        });

        panel.add(usernameField);
        JLabel passwordLabel = new JLabel("密码");
        panel.add(passwordLabel);
        final JPasswordField passwordField = new JPasswordField(20);
        panel.add(passwordField);

        JLabel verifyCodeLabel = new JLabel("验证码");
        panel.add(verifyCodeLabel);

        panel.add(verifyCodeData);

        panel.add(verifyCodeField);

        JButton button = new JButton("登陆");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                webQq.login(passwordField.getText(), verifyCodeField.getText());
                webQq.login2();
                loadFriends();
                webQq.poll2(new MessageHandler() {
                    public void hand(Poll2Response response) {
                        System.err.println(response.getBody());
                        showMessage(response.getMessage());
                    }
                });
            }
        });
        panel.add(button);

        tabbedPane.addTab("登陆", panel);
    }

    private void showMessage(Message message) {
        User user = getUser(message.getFrom_uin());
        // JPanel panel = getChatPanel(user);
        // writeMessage(panel, user, message);
    }

    private void writeMessage(JPanel panel, User user, Message message) {
        for (Component component : panel.getComponents()) {
            if (component instanceof JTextArea) {
                JTextArea textArea = (JTextArea) component;
                textArea.append(user.getNick() + "说:\n" + message.getContent());
            }
        }
    }

    private User getUser(String uin) {
        for (User user : this.users) {
            if (user.getUin().equals(uin)) {
                return user;
            }
        }
        return null;
    }

    private void loadFriends() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        GetUserFriends2Response response = webQq.getUserFriends2();
        System.err.println(response.getBody());
        List<User> users = response.getUsers();
        this.users = users;
        for (User user : users) {
            panel.add(getUserLabel(user));
        }
        tabbedPane.addTab("好友", panel);
        tabbedPane.setSelectedComponent(panel);
    }

    /**
     * 用户列表的一个用户
     */
    private JButton getUserLabel(final User user) {
        JButton button = new JButton(user.getNick() + " (" + user.getMarkname() + ")");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                getChatPanel(user);
            }
        });
        return button;
    }

    private JPanel getChatPanel(User user) {
        JPanel panel;
        for (int i = 0; i < tabbedPane.getTabCount(); i++) {
            if ("聊天".equals(tabbedPane.getTitleAt(i))) {
                panel = (JPanel) tabbedPane.getComponentAt(i);
                tabbedPane.setSelectedComponent(panel);
                return getChatPabelOne(panel, user);
            }
        }
        panel = new JPanel();
        tabbedPane.addTab("聊天", panel);
        tabbedPane.setSelectedComponent(panel);
        return getChatPabelOne(panel, user);
    }

    private JPanel getChatPabelOne(JPanel panel, User user) {
        JTabbedPane chartTabbedPane;
        Component[] components = panel.getComponents();
        if (components == null || components.length < 1) {
            chartTabbedPane = new JTabbedPane(JTabbedPane.LEFT);
            panel.add(chartTabbedPane);
        } else {
            chartTabbedPane = (JTabbedPane) panel.getComponent(0);
        }
        for (int i = 0; i < chartTabbedPane.getTabCount(); i++) {
            if (user.getNick().equals(chartTabbedPane.getTitleAt(i))) {
                JPanel panel2 = (JPanel) chartTabbedPane.getComponentAt(i);
                chartTabbedPane.setSelectedComponent(panel2);
                return panel;
            }
        }

        JPanel chartPanel = new JPanel();
        chartPanel.setLayout(new BoxLayout(chartPanel, BoxLayout.Y_AXIS));
        JTextArea recive = new JTextArea("收到的消息 " + user.getNick());
        recive.setEditable(false);
        recive.setRows(25);
        recive.setColumns(80);
        chartPanel.add(recive);

        // 作分隔带用
        JButton button = new JButton(" ");
        button.setEnabled(false);
        chartPanel.add(button);

        JTextArea send = new JTextArea("我要发的消息 " + user.getNick());
        send.setRows(5);
        send.setColumns(80);
        chartPanel.add(send);
        chartPanel.add(new Button("Send"));

        chartTabbedPane.addTab(user.getNick(), chartPanel);
        chartTabbedPane.setSelectedComponent(chartPanel);
        return chartPanel;
    }

    private void addTrayIcon() throws Exception {
        trayIcon = new TrayIcon(ImageIO.read(new URL("http://www.easyicon.net/api/resize_png_new.php?id=1114560&size=24")));
        trayIcon.setToolTip("提示信息");
        trayIcon.setImageAutoSize(true);
        SystemTray.getSystemTray().add(trayIcon);
    }

    protected void processWindowEvent(WindowEvent e) {
        if (e.getID() == WindowEvent.WINDOW_CLOSING) {
            if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this, "确认退出?")) {
                SystemTray.getSystemTray().remove(trayIcon);
                System.exit(0);
            }
        } else {
            super.processWindowEvent(e);
        }
    }
}